import { onMounted, reactive } from 'vue';
import {
  getCommentListService,
  setCommentListService
} from '../service/comment';

class Comment {
  constructor(opt) {
    this.getterUrl = opt.getterUrl;
    this.setterUrl = opt.setterUrl;
    this.state = reactive({
      commentText: '',
      commentTree: null
    });
    this.addComment = this.addComment.bind(this);
    this.addReply = this.addReply.bind(this);
    this.setComment = this.setComment.bind(this);

    this.getCommentTree();
  }

  //原型方法
  getCommentTree() {
    onMounted(async () => {
      const commentList = await this.getCommentList();
      this.state.commentTree = Comment.formatTree(commentList);
    });
  }

  async getCommentList() {
    return await getCommentListService(this.getterUrl);
  }

  addComment({ id, username }) {
    const commentInfo = {
      id: new Date().getTime(),
      uid: id,
      pid: 0,
      username,
      comment: this.state.commentText
    };
    this.setCommentList(commentInfo, this.setComment);
  }

  async setCommentList(comment, callback) {
    const data = await setCommentListService(this.setterUrl, { comment });
    // console.log(data);
    //{id: '1677654493172', uid: '1', pid: '0', username: 'icy', comment: '111'}
    callback && callback(data);
  }

  setComment(comment) {
    this.state.commentTree.unshift(comment);
    this.state.commentText = '';
  }

  addReply(item, replyText, { id, username }) {
    // console.log(item, replyText, id, username);
    //{id: '1677656722137', uid: '3', pid: '0', username: 'Jerry', comment: '333', …} '222' 1 'icy'
    const replyInfo = {
      id: new Date().getTime(),
      uid: id,
      pid: item.id,
      username,
      comment: replyText
    };

    this.setCommentList(replyInfo, (reply) => {
      this.setReply(item, reply);
    });
  }

  setReply(item, reply) {
    // console.log(item);
    //{id: children: [{…}, {…}], '1677656255700', uid: '1', pid: '0', username: 'icy', comment: '111', …}
    // console.log(reply);
    //{id: '1677658058861', uid: '1', pid: '1677656722137', username: 'icy', comment: '444'}
    (item.children || (item.children = [])).unshift(reply);
    item.replyText = '';
  }

  //静态方法
  static formatTree(data) {
    // console.log(data);
    //[{id: '1677654631372', uid: '1', pid: '0', username: 'icy', comment: '111'}]
    const result = [];
    const map = {};

    data.forEach((item) => {
      map[item.id] = item;
    });

    // console.log(map);
    //{1677639922904: {id: '1677639922904', uid: '1', pid: '0', username: 'icy', comment: '111'}}

    data.forEach((item) => {
      const parent = map[item.pid];
      // console.log(parent); 假如pid为0即不存在该值为undefined
      if (parent) {
        (parent.children || (parent.children = [])).push(item);
      } else {
        result.push(item);
      }
    });

    return result;
  }
}

export default Comment;
